package com.bank.service.impl;

import com.bank.constant.AccountStatus;
import com.bank.constant.MessageConstant;
import com.bank.constant.TransactionType;
import com.bank.dto.AccountDTO;
import com.bank.dto.AccountOperationDTO;
import com.bank.entity.Account;
import com.bank.entity.BillTransaction;
import com.bank.entity.User;
import com.bank.exception.*;
import com.bank.mapper.AccountMapper;
import com.bank.mapper.BillTransactionMapper;
import com.bank.mapper.UserMapper;
import com.bank.service.AccountService;
import com.bank.vo.AccountLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<AccountLoginVO> getAllAccountInfoByUserId(Long userId) {
        return accountMapper.getAllAccountsByUserId(userId);
    }


    // 检验用户信息是否完整，满足条件才能创建账户
    @Override
    public void checkUserInfo(Long userId) {
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new UserNotFoundException(MessageConstant.USER_NOT_FOUND);
        }

        if (user.getRealName() == null || user.getIdNumber() == null || user.getPhone() == null) {
            throw new UserIncompleteInfoException(MessageConstant.USER_INCOMPLETE_INFO);
        }
    }

    @Transactional
    @Override
    public Long addAccount(AccountDTO accountDTO) {
        // 检验用户信息是否完整
        checkUserInfo(accountDTO.getUserId());

        // 持有卡数量限制
        Integer number = accountMapper.getAccountNumberByUserId(accountDTO.getUserId());
        Integer maxNumber = userMapper.gteMaxAccountNumber(accountDTO.getUserId());
        if (number != null && number.equals(maxNumber)) {
            throw new AccountMaxLimitException(MessageConstant.ACCOUNT_MAX_LIMIT_EXCEEDED);
        }
          // 用户是否存在
//        if (number == null) {
//            throw new UserNotFoundException(MessageConstant.USER_NOT_FOUND);
//        }

        Account account = new Account();
        BeanUtils.copyProperties(accountDTO, account);
        // 密码加密
        account.setPassword(DigestUtils.md5DigestAsHex(account.getPassword().getBytes()));
        LocalDateTime now = LocalDateTime.now();
        account.setCreateTime(now);
        account.setUpdateTime(now);

        accountMapper.addAccount(account);

        return account.getAccountId();
    }

    @Override
    public void updateTimeByAccountId(Long accountId) {
        LocalDateTime now = LocalDateTime.now();
        accountMapper.updateTimeByAccountId(accountId, now);
    }
}
